package com.fitbet.wechat.web.controller.auth;

import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.handler.CookieHandler;
import com.fitbet.entity.user.User;
import com.fitbet.wechat.Constant;
import com.fitbet.wechat.handler.SmsHandler;
import com.fitbet.wechat.service.UserService;

/**
 * 
 * @author mohanlan
 *
 */
@Controller()
@RequestMapping("/login")
public class MobileLoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(MobileLoginController.class);
    
    public static final String MOBILE = Constant.MOBILE_KEY;
    
    public static final int EXPIRE_TIME = 1080 * 24 * 3600;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private SmsHandler smsHandler;
    
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult mobileLogin(@RequestParam("unionid") String unionid,
                                                @RequestParam("mobile") String mobile,
                                                @RequestParam("token") String token,
                                                @RequestParam("code") String code,
                                                HttpServletResponse response) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            boolean result = smsHandler.checkVerifyCode(mobile, code, token);
            
            if(!result) {
                httpResult.fail("500").message("验证码不正确");
                return httpResult;
            }
            
            User user = userService.loadUser(unionid);
            
            if(org.apache.commons.lang3.StringUtils.isBlank(user.getMobile())) {
                userService.bindUserMobile(user, mobile);
            }
            
            cookieHandler.addCookie(response, MOBILE, mobile, EXPIRE_TIME);
            
            httpResult.success().message("验证手机成功");
            
        } catch (Exception e) {
            
            logger.error("#verifyUserMobile() occurs error", e);
            
            httpResult.fail("500").message("验证手机失败");
            
        }
        
        return httpResult;
    }
    
}
